# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from random import Random

from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from EduOnline.settings import EMAIL_FROM


def is_expired(expire_time):
	"""是否过期，设置url时间有效性"""
	if isinstance(expire_time, str):  # 判断`expire_time`与`str`类型是否相同，如果同则进行时间格式化
		expire_time = datetime.datetime.strptime(expire_time, '%Y-%m-%d %H:%M:%S')

	delta_time = datetime.datetime.now() - expire_time
	if delta_time.days >= 0:  # `.days`所得结果是时分秒的加减总和（不单单是时位上的加减）；`.seconds`所得结果是分秒的加减总和
		# print('expired')
		return True

	else:
		# print('valid')
		return False


def random_str(random_length=8):
	"""生成随机数函数"""
	str = ''
	chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
	length = len(chars) - 1
	random = Random()
	for i in range(random_length):
		str += chars[random.randint(0, length)]  # 从自定义chars中随机取出一位
	return str


def send_email(email, send_type='register'):
	# 保存邮件内容
	email_record = EmailVerifyRecord()
	code = random_str(16)
	email_record.code = code
	email_record.email = email
	email_record.send_type = send_type
	email_record.save()

	# 发送邮件
	email_title = ''  # 主题
	email_body = ''  # 内容

	if send_type == 'register':  # 注册
		email_title = '在线教育网注册激活链接'
		email_body = '您已注册`EduOnlie`（在线教育网），待激活完成注册...>>>请点击（或复制到浏览器打开）下面的链接激活您的帐号：http://127.0.0.1:8000/activeuser/{0}'.format(code)

		send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
		if send_status:
			pass

	if send_type == 'forgetpwd':  # 重置
		email_title = '在线教育网密码重置链接'
		email_body = '>>>请点击（或复制到浏览器打开）下面的链接重置密码：http://127.0.0.1:8000/resetpwd/{0}'.format(code)

		send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
		if send_status:
			pass
